package cn.itsource.config;

import cn.hutool.core.util.IdUtil;
import cn.itsource.constants.RConst;
import cn.itsource.domain.Login;
import cn.itsource.mapper.LoginMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class BootstrapListener  implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

	@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Login login = new Login();
        login.setId(IdUtil.createSnowflake(RConst.Num.INT_1,RConst.Num.INT_1).nextId());
        login.setUsername("admin");
        login.setPassword(passwordEncoder.encode("123456"));
        login.setType(RConst.Num.INT_0);
        login.setEnabled(true);
        login.setAvatar("http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280");
        login.setAdmin(true);
        login.setNickName("admin");
        //查询 数据库是否初始化 初始化 就不需要初始化了
        Login login1 = loginMapper.selectOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, login.getUsername())
                .eq(Login::getType, login.getType())
                .eq(Login::getAdmin, login.getAdmin()));
        if (login1==null){
            loginMapper.insert(login);
        }
    }
}